package messy.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author jiaqi.han
 * @date 2021年3月11日
 */
public class Student extends HttpServlet {

	private static final long serialVersionUID = 1L;

	// 上传配置
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("流程正常!");

		// 检测是否为多媒体上传
		if (!ServletFileUpload.isMultipartContent(req)) {
			// 如果不是则停止
			PrintWriter writer = resp.getWriter();
			writer.println("Error: 表单必须包含 enctype=multipart/form-data");
			writer.flush();
			return;
		}

		// 配置上传参数
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		// 设置临时存储目录
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

		ServletFileUpload upload = new ServletFileUpload(factory);

		// 设置最大文件上传值
		upload.setFileSizeMax(MAX_FILE_SIZE);

		// 设置最大请求值 (包含文件和表单数据)
		upload.setSizeMax(MAX_REQUEST_SIZE);

		// 中文处理
		upload.setHeaderEncoding("UTF-8");

		// 构造临时路径来存储上传的文件
		// 这个路径相对当前应用的目录
		String uploadPath = "E:\\File";

		// 如果目录不存在则创建
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}

		try {
			// 解析请求的内容提取文件数据
			List<FileItem> formItems = upload.parseRequest(req);

			if (formItems != null && formItems.size() > 0) {
				// 迭代表单数据
				for (FileItem item : formItems) {
					// 处理不在表单中的字段
					if (!item.isFormField()) {
						String fileName = new File(item.getName()).getName();
						String filePath = uploadPath + File.separator + fileName;
						File storeFile = new File(filePath);
						// 读取文件内容并在控制台显示
						displayStudentInformation(storeFile);
						// 在控制台输出文件的上传路径
						System.out.println(filePath);
						// 保存文件到硬盘
						item.write(storeFile);
						getServletContext().getRequestDispatcher("/success.jsp").forward(req, resp);
					}
				}
			}
		} catch (Exception ex) {
			getServletContext().getRequestDispatcher("/failed.jsp").forward(req, resp);
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

	/**
	 * 获取文件中,学生的信息.如果文件表头格式有误,在后台提示.在表头无误的情况下,将内容格式正确的记录输出,将格式错误的指出
	 * @author jiaqi.han
	 * @throws IOException 
	 * @date 2021年3月11日
	 */
	public void displayStudentInformation(File file) throws IOException {
		InputStream is = new FileInputStream(file);
		XSSFWorkbook workbook = new XSSFWorkbook(is);

		// 循环读取表
		int sheetNum = workbook.getNumberOfSheets();
		for (int i = 0; i < sheetNum; i++) {
			Sheet sheet = workbook.getSheetAt(i);
			// 循环读取行
			int rowNum = sheet.getLastRowNum();
			for (int j = 0; j < rowNum + 1; j++) {
				// 如果是第一行,说明是表头,读取表头,放入容器中,用于比较
				if (j == 0) {
					Set<String> headSet = new HashSet<String>();
					Row headRow = sheet.getRow(0);
					int cellNum = headRow.getLastCellNum();
					for (int k = 0; k < cellNum; k++) {
						// 操作每一个单元格
						Cell cell = headRow.getCell(k);
						String name = cell.toString();
						headSet.add(name);
					}
					judgeFileHead(headSet);
				}

//				Row row = sheet.getRow(j);
//				// 循环读取列
//				int cellNum = row.getLastCellNum();
//				for (int k = 0; k < cellNum; k++) {
//					// 操作每一个单元格
//					Cell cell = row.getCell(k);
//					if (k == 3 && j != 0) {
//						String name = row.getCell(0).toString();
//						String mindex = "";
//						String newmindex = "";
//						if (row.getCell(3) != null) {
//							mindex = row.getCell(3).toString();
//							newmindex = name + "," + mindex;
//						} else {
//							newmindex = name;
//						}
//					}
//				}
			}
		}

		// 写出文件
		OutputStream os = new FileOutputStream("e:\\file2.xlsx");
		os.close();
		is.close();
		workbook.close();
	}

	/**
	 * 判断传来的Set容器中的内容,是否包含给定的数组内容,如果全部包含,则返回true,否则返回false
	 * @author jiaqi.han
	 * @date 2021年3月11日
	 */
	private boolean judgeFileHead(Set<String> headSet) {
		System.out.println(headSet.toString());
		return false;
	}

}
